﻿using ObjectPool;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class Platform_Breakable : Platform_Energy
{
    private ObjectManager objectManager;
    private TilemapRenderer m_renderer;
    private TilemapCollider2D m_collider;

    private float breakSpeed = 1f;

    [SerializeField]
    private bool _Broken;
    public bool Broken
    {
        get => _Broken;
        set
        {
            m_renderer.enabled = !value;
            m_collider.enabled = !value;
            canvas.gameObject.SetActive(!value);
            _Broken = value;
        }
    }

    protected override void OnStart()
    {
        objectManager = Service.Get<ObjectManager>();
        m_renderer = GetComponent<TilemapRenderer>();
        m_collider = GetComponent<TilemapCollider2D>();
        base.OnStart();
    }

    protected override void OnPlayerDie()
    {
        Broken = false;
    }

    protected override void OnPlayerCollide(Vector2 normalLine, GameObject platform, Character player)
    {
        base.OnPlayerCollide(normalLine, platform, player);
        BreakTiles(-normalLine, player.transform.position); 
        Broken = true;
    }

    public void BreakTiles(Vector2 drct_hit,Vector3 hitPoint)
    {
        StartCoroutine(BreakTiles_(drct_hit, hitPoint));
    }

    public IEnumerator BreakTiles_(Vector2 drct_hit, Vector3 hitPosition)
    {
        List<Vector3Int> tilePositions = cTilemap.GetAllPosition();
        List<TileBase> tiles = cTilemap.GetAll();

        //碎片飞出的方向
        Vector2 drct_move;      
        //碰撞点到碎片的方向
        Vector2 drct_fragment;
        //表面方向（即法线的垂线）
        Vector2 drct_surface = new Vector2(drct_hit.y, drct_hit.x);

        //冲击波传递的速度
        float speed_shockwave = 0.2f * Character.Instance.Velocity_LastFixedUpdate.magnitude;
        //冲击波已传递的距离
        float distance_shockwave = 0;

        List<Fragment> fragments = new List<Fragment>();
        Vector3Int tilePosition;

        //拆散平台
        for (int i = 0; i < tilePositions.Count; i++)
        {
            tilePosition = tilePositions[i];
            fragments.Add((Fragment)objectManager.Activate(EObject.BrokenTilemap, tilePosition));
        }

        Fragment fragment;
        
        //碎片由近到远依次飞出
        for (; ; )
        {
            distance_shockwave += Time.fixedDeltaTime * speed_shockwave;
            for (int i = 0; i < tilePositions.Count; i++)
            {
                tilePosition = tilePositions[i];
                if((tilePosition-hitPosition).magnitude<distance_shockwave)
                {
                    fragment = fragments[i];
                    drct_fragment = tilePosition - hitPosition;
                    drct_move = (drct_fragment + Vector3.Project(drct_fragment, drct_surface).RemoveZ()).normalized;
                    fragment.Move(drct_move, breakSpeed, 0.5f);

                    tilePositions.RemoveAt(i);
                    fragments.RemoveAt(i);
                    if (fragments.Count == 0)
                        yield break;
                }
            }
            yield return null;
        }
    }
}
